﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.cms.businesslogic.web;
using AutoFolders.Providers;
using umbraco.cms.businesslogic;
using System.Xml.XPath;

namespace AutoFolders 
{
    public class ApplicationBase : umbraco.BusinessLogic.ApplicationBase 
    {
         /// <summary>
        /// Initializes a new instance of the <see cref="ApplicationBase"/> class.
        /// </summary>
        public ApplicationBase()
        {
            Document.New += new Document.NewEventHandler(Document_New);
            Document.AfterPublish += new Document.PublishEventHandler(Document_New);
        }

        void Document_New(Document sender, object e)
        {
            Document documentObject = sender;

            // Check DocType
            string documentTypeAlias = documentObject.ContentType.Alias;
            if (AutoFolderSettings.Instance.IsEffectedDocType(documentTypeAlias))
            {
                AutoFolderSetting autoFolder = AutoFolderSettings.Instance.GetSettings(documentTypeAlias);
                
                int parentId = documentObject.Parent.Id;
				int rootID = parentId;

                // Additional check if creation is restricted via a root folder
                if (!String.IsNullOrEmpty(autoFolder.RootFolders))
                {
                    rootID = ValidParentFolder(documentObject, autoFolder.RootFolders);
                }
                 
                if (rootID > -1)
                {
                    // Check if Parent Folder Structure is correct... 
                    int newParentFolderId = autoFolder.FolderProvider.FindValidFolderId(documentObject, rootID);
                    if (newParentFolderId <= 0)
                    {
                        // Create Valid Structure
                        newParentFolderId = autoFolder.FolderProvider.CreateFolderStructure(documentObject, rootID, autoFolder.FolderDocType);
                    }

                    // Move document to new folder
                    if (parentId != newParentFolderId)
                    {
                        documentObject.Move(newParentFolderId);

                        // Republish 
                        documentObject.Publish(documentObject.User);
                        umbraco.library.UpdateDocumentCache(documentObject.Id);
                    }
                }
            }
        }

        private int ValidParentFolder(Document documentObject, string rootFolders)
        {
            if (documentObject.Parent == null)
                return -1;

            int parentId = documentObject.Parent.Id;

            string rootFolderXPath = rootFolders.Trim();
            if(rootFolderXPath.StartsWith("//node"))
                rootFolderXPath = rootFolderXPath.Substring(6);
            if(rootFolderXPath.StartsWith("/node"))
                rootFolderXPath = rootFolderXPath.Substring(5);

            XPathNodeIterator parentNode = umbraco.library.GetXmlNodeById(documentObject.Parent.Id.ToString());
            XPathNodeIterator safeRootNodes = parentNode.Current.Select("ancestor-or-self::node" + rootFolderXPath);

            if(safeRootNodes.MoveNext())
            {
                int firstParentId = Convert.ToInt32(safeRootNodes.Current.GetAttribute("id",""));

                while (safeRootNodes.MoveNext())
                {
                    firstParentId = Convert.ToInt32(safeRootNodes.Current.GetAttribute("id",""));
                }

                return firstParentId;
            }
            else
            {
                return -1;
            }
        }

    }
}
